<template>
  <div class="main-header el-header">
    <div class="app-header">
      <div class="top-header">
        <div class="flex-row menubar">
          <div class="flex-item navbar">
            <top-menu :menus="currentMenus" :maxShowNumber="5"></top-menu>
          </div>
          <el-form v-if="esIsOpen" :model="fullSearch" style="margin-top: 10px">
            <el-form-item class="mr20 sh">
              <el-input
                @keyup.enter.native="searchPage"
                v-model="fullSearch.keywords"
                placeholder="全文检索"
              >
                <i
                  slot="suffix"
                  id="searchIcon"
                  class="fa fa-search mr10"
                  style="font-size: 18px"
                  @click="searchPage"
                ></i>
              </el-input>
            </el-form-item>
          </el-form>
          <div class="line_v"></div>
          <div>
            <div class="leader_status" v-if="false">
              <div
                align="center"
                style="color: #99B4CA;width: auto;height:32px;line-height:32px;float:left;"
              >
                领导状态：
              </div>
              <div
                align="center"
                style="color: #0075FF;width: auto;height:32px;line-height:32px;float: left"
              >
                开会中
              </div>
            </div>
            <div class="theme_div" v-if="false">
              <div
                align="center"
                style="color: #0075FF;width: auto;height:32px;line-height:32px;float: left"
              >
                <top-theme
                  @change="themeChange"
                  style="margin-top: 3px;float:left;margin-right: 10px;"
                ></top-theme>
                <el-badge
                  :value="noticeCount"
                  class="item"
                  type="warning"
                  v-if="false"
                >
                  <i
                    class="el-icon-message-solid icon-color"
                    style="font-size: 124%;margin-right: 10px;"
                  ></i>
                </el-badge>
              </div>
            </div>
            <div class="leader_status" @click="openDang" v-if="false">
              <img
                src="@/assets/dang.png"
                style="width:auto;height: 20px;float:left;margin-right: 3px;margin-top: 4px;"
              />
              <div
                align="center"
                style="width: auto;;float:left;line-height: 32px;height: 32px;color: #99B4CA;"
              >
                党建
              </div>
            </div>
            <div class="leader_status">
              <el-avatar
                :src="avatar"
                style="width: 32px;height: 32px;float:left;margin-right: 5px;"
              ></el-avatar>
              <el-dropdown
                trigger="hover"
                :show-timeout="10"
                style="line-height: 35px;float: left"
              >
                <span class="el-dropdown-link userinfo-inner">
                  {{ adminDisplayName
                  }}<i class="el-icon-caret-bottom el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown" style="margin-right: 16px;">
                  <el-dropdown-item @click.native="goChangePassword">
                    <i
                      class="fa fa-unlock-alt mr10 ico-s"
                      aria-hidden="true"
                    ></i>
                    <span>修改密码</span>
                  </el-dropdown-item>
                  <el-dropdown-item divided @click.native="logout">
                    <i class="fa fa-sign-out mr10 ico-s" aria-hidden="true"></i>
                    <span>退出登录</span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      :visible.sync="showChangePwd"
      title="修改密码"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-card>
        <el-form
          ref="form"
          :model="passForm"
          label-width="80px"
          class="demo-form"
        >
          <el-form-item
            prop="oldPassword"
            label="原密码"
            :rules="[
              {
                required: true,
                message: '请填写原密码',
                trigger: 'change,blur'
              },
              { min: 6, message: '密码长度至少6位', trigger: 'blur' }
            ]"
          >
            <el-input type="password" v-model="passForm.oldPassword"></el-input>
          </el-form-item>

          <el-form-item
            prop="newPassword"
            label="新密码"
            :rules="[
              {
                required: true,
                message: '请设置新密码',
                trigger: 'change,blur'
              },
              { validator: validatePassword, trigger: 'blur' }
            ]"
          >
            <el-input type="password" v-model="passForm.newPassword"></el-input>
          </el-form-item>

          <el-form-item
            prop="rePassword"
            label="重复密码"
            :rules="[
              {
                required: true,
                message: '请再次填写新密码',
                trigger: 'change,blur'
              },
              { validator: validateRePass, trigger: 'change,blur' }
            ]"
          >
            <el-input type="password" v-model="passForm.rePassword"></el-input>
          </el-form-item>

          <el-form-item>
            <span>
              <el-button size="small" round type="primary" @click="submit"
                >提交</el-button
              >
              <el-button
                size="small"
                round
                type="default"
                @click="showChangePwd = false"
                >返回</el-button
              >
            </span>
          </el-form-item>
        </el-form>
      </el-card>
    </el-dialog>
    <el-dialog
      :visible.sync="noticeVisible"
      title="消息提醒"
      width="500px"
      @close="noticeRead"
    >
      <div class="notice">
        <span>{{ curNotice.content }}</span>
      </div>
      <div class="notice_btn">
        <span>
          <el-button size="small" type="primary" @click="noticeRead"
            >标记已读</el-button
          >
          <el-button size="small" type="default" @click="noticeRead"
            >返回</el-button
          >
        </span>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import _ from "lodash";
import md5 from "js-md5";
import "@/libs/ArrayUtil";
import avatar from "../../assets/man.png";
export default {
  name: "page-header",

  mounted() {
    // this.updateUserMenus();
    this.getUserInfo();
    this.getESIsOpen();
    this.getSystemSetting();
    // this.getNewNotice()
  },
  watch: {
    showChangePwd(val) {
      if (!val) {
        this.passForm = {
          oldPassword: "",
          newPassword: "",
          rePassword: ""
        };
      }
    }
  },
  data() {
    return {
      avatar,
      fullSearch: {
        keywords: ""
      },
      noticeVisible: false,
      curNotice: {},
      noticeCount: 0,
      showChangePwd: false,
      webTitle: this.$appConf.appTitle,
      esIsOpen: false,
      passForm: {
        oldPassword: "",
        newPassword: "",
        rePassword: ""
      },
      // 密码正则校验
      passwordTest: "",
      passwordTestMessage: "",
      validatePassword: (rule, value, callback) => {
        if (!this.passwordTest) {
          callback();
          return;
        }
        if (!value) {
          callback(new Error(`密码不能为空`));
        }
        if (!eval(`/${this.passwordTest}/`).test(value)) {
          callback(new Error(`${this.passwordTestMessage}`));
          return;
        }
        if (value.length < 6) {
          callback(new Error(`密码最少设置6位`));
        }
        callback();
      },
      validateRePass: (rule, value, callback) => {
        if (value !== this.passForm.newPassword) {
          callback(new Error("两次输入密码不一致!"));
        } else {
          callback();
        }
      }
    };
  },
  props: {
    menus: {
      type: Array
    }
  },
  computed: {
    ...mapGetters({
      adminInfo: "adminInfo",
      currentIndex: "currentIndex",
      userMenus: "userMenus",
      currentTokenUser: "currentTokenUser",
      sysTheme: "sysTheme",
      allPrompt: "allPrompt"
    }),
    adminDisplayName() {
      return this.currentTokenUser.user == null
        ? ""
        : this.currentTokenUser.user.name;
    },
    currentMenus() {
      let tem = _.cloneDeep(this.userMenus);
      if (tem) {
        tem.map((item, index) => {
          if (item.menus && item.menus.length > 0) {
            var path = this.getFirstOneMenu(item.menus);
            item.path = path;
          }
          item.menus = [];
        });
      }
      return tem;
    }
  },
  methods: {
    // 获取应用配置(密码正则)
    getSystemSetting() {
      let obj = {
        id: 1
      };
      this.API.getSystemSettingById(obj).then(res => {
        let { data } = res;
        if (!data) {
          return;
        }
        let { passwordRegular, passwordRegularMessage } = data;
        this.passwordTest = passwordRegular;
        this.passwordTestMessage = passwordRegularMessage;
      });
    },
    //点击搜索
    searchPage() {
      this.$store
        .dispatch("setFullSearch", this.fullSearch.keywords)
        .then(() => {
          this.$router.push({
            name: "globalSearchIndex"
          });
          this.fullSearch.keywords = "";
        });
    },
    //是否开启es
    getESIsOpen() {
      this.API.getSystemSettingES().then(ret => {
        this.esIsOpen = ret.data;
      });
    },
    // 打开党建
    openDang() {},
    // 主题切换
    themeChange(val) {
      this.$store.dispatch("set_theme", val).then(res => {});
      this.API.updateThemeColor({ color: val }).then(res => {});
    },
    // 标记已读
    noticeRead() {
      this.API.readNoticeUsingPOST({
        saveReadNoticeDto: { id: this.curNotice.id, readFlag: true }
      }).then(res => {
        this.noticeVisible = false;
      });
    },
    // 获取最新的通知
    getNewNotice() {
      return setInterval(() => {
        if (this.noticeVisible) {
          return;
        } else {
          if (window.sessionStorage.getItem("token")) {
            this.API.noticeMyListUsingPOST({
              baseNoticeSerachDto: { readFlag: "1" }
            }).then(res => {
              let tem = res.data;
              this.noticeCount = tem.totalRow;
              if (tem.list && tem.list.length > 0) {
                this.noticeVisible = false;
                this.curNotice = tem.list[0];
              } else {
                this.curNotice = {};
                this.noticeVisible = false;
              }
            });
          }
        }
      }, 10000);
    },
    // 获取用户信息
    getUserInfo() {
      this.$store.dispatch("userInfoUsingPOSTS").then(res => {
        // Todo 从数据库取用户主题
        if (res.data.user.themeColor) {
          this.$store
            .dispatch("set_theme", res.data.user.themeColor)
            .then(res => {});
        }
        this.connect();
      });
    },
    // 设置菜单的数量属性
    setMenuCount(item, data) {
      if (data) {
        data.map((waitItem, index) => {
          if (waitItem.key === item.key) {
            this.$set(item, "count", waitItem.value);
          } else {
            if (item.children) {
              item.children.map(itemSub => {
                this.setMenuCount(itemSub, data);
              });
            }
          }
        });
      }
    },
    // 连接socket
    connect() {
      const socketUrl =
        window.api.socketUrl +
        JSON.parse(window.sessionStorage.getItem("userInfo")).user.userId +
        "?token=" +
        window.sessionStorage.getItem("token");

      this.socket = new WebSocket(socketUrl);
      // 监听socket打开
      this.socket.onopen = function() {
        console.log("浏览器WebSocket已打开");
      };
      let that = this;
      // 监听socket消息接收
      this.socket.onmessage = function(msg) {
        // 转换为json对象
        const data = JSON.parse(msg.data);
        console.log(data, "socket");
        switch (data.type) {
          case "WORKFLOW_COUNT_CHANGE":
          case "SUPERVISION_COUNT_CHANGE":
          case "ANNOUNCEMENT_COUNT_CHANGE":
          case "DOCUMENT_COUNT_CHANGE":
          case "KNOWABLE_COUNT_CHANGE":
          case "MEETING_COUNT_CHANGE":
          case "DOCUMENT_COUNT_AUDIT_CHANGE":
            if (data.message) {
              if (
                data.message.type === "PLUS" ||
                data.message.type === "DEFAULT"
              ) {
                that.playVideo();
                that.warning(data.message.message);
              }
              that.allPrompt.map(item => {
                data.message.list.map(item1 => {
                  if (item.key === item1.key) {
                    if (data.message.type === "PLUS") {
                      item.value += 1;
                    } else if (data.message.type === "MINUS") {
                      item.value -= 1;
                    }
                  }
                });
              });
              that.$store.dispatch("updatePromptCount", that.allPrompt);
              that.userMenus.map(item => {
                that.setMenuCount(item, that.allPrompt);
              });
              that.$store
                .dispatch("updateUserMenus", that.userMenus)
                .then(res => {});
            }
            break;
        }
      };
      // 监听socket错误
      this.socket.onerror = function() {
        that.$notify({
          title: "错误",
          message: "服务器异常，SOCKET已断开",
          type: "error",
          duration: 0
        });
      };
      // 监听socket关闭
      this.socket.onclose = function() {
        console.log("WebSocket已关闭");
      };
    },
    submit() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.$store
            .dispatch("changePassword", {
              password: md5(this.passForm.oldPassword),
              newPassword: md5(this.passForm.newPassword)
            })
            .then(ret => {
              this.$notify({
                title: "密码修改成功",
                type: "success"
              });
              this.showChangePwd = false;
            });
        }
      });
    },

    logout() {
      this.$confirm("确认退出吗?", "提示", {})
        .then(() => {
          let appKey = window.sessionStorage.getItem("appKey");
          this.$store.dispatch("cleanInfo");
          window.localStorage.setItem("clearInfo", "clear");
          window.location.href = "/";
        })
        .catch(() => {});
    },
    goChangePassword() {
      this.showChangePwd = true;
    },
    goMessage() {
      this.$router.push({ name: "newsMessage" });
    }
  },
  components: {}
};
</script>

<style scoped lang="scss">
@import "../../styles/vars";
.demo-form{
  .el-form-item{
    margin-bottom: 30px;
  }
}
.theme_div {
  width: auto;
  height: 32px;
  float: left;
  margin-top: 13px;
}

.leader_status {
  width: auto;
  height: 32px;
  float: left;
  background-color: $main-bg;
  border-radius: 6px;
  margin-top: 8px;
  margin-bottom: 6px;
  padding: 6px 16px;
  text-align: center;
  margin-right: 10px;
  cursor: pointer;
}

.notice {
  border: 1px solid #cecece;
  padding: 20px;
  border-radius: 5px;
}

.notice_btn {
  text-align: center;
  padding: 20px;
}

.ico-s {
  width: 14px;
  height: 14px;
  text-align: center;
}

.main-header {
  width: 100%;
  background-color: white;
  height: 60px;
  min-width: 1136px;
}

.navbar {
  max-width: 880px;
  height: 60px;
  margin: 0 auto 0 40px;
}

.app-header {
  background-color: transparent;
  min-width: 880px;
  margin: 0 auto;
}

.menubar {
  max-width: 100%;
  /*<!--background-color: $color-primary;-->*/
  margin: 0 auto;
}

.top-header {
  background-color: transparent;
  min-width: 880px;
}

.el-menu.el-menu--horizontal {
  background-color: transparent !important;
  border-bottom: none;

  .el-menu-item {
    background-color: transparent !important;
  }
}

.nav-logo {
  width: auto;
  /*height: 33px;*/
  padding: 15px;
  line-height: 33px;
}

.navbar-color-bg-a {
  color: #fff;
  text-decoration: none;
  border: 0;
  border-radius: 4px;
  cursor: pointer;
}

.badge {
  display: inline-block;
  min-width: 10px;
  padding: 3px 7px;
  font-size: 24px;
  font-weight: 700;
  line-height: 1;
  color: #fff;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  background-color: #777;
  border-radius: 10px;
}

.tools {
  padding: 0 23px 0 0;
  height: 64px;
  line-height: 64px;
  cursor: pointer;
  display: inline-block;
  color: #fff;
  font-size: 16px;
}

.userinfo-inner {
  font-size: 16px;
  color: #000000;
}

.msg-count {
  background-color: red;
  position: relative;
  left: -22px;
  top: -10px;
  font-weight: 200;
  transform: scale(0.75, 0.75);
}

/deep/ .el-menu-item:focus,
/deep/ .el-menu-item:hover {
  background-color: transparent !important;
}

.item {
  /deep/ .el-badge__content.is-fixed {
    top: 5px !important;
    right: 20px !important;
  }
}

#searchIcon:hover {
  color: #409eff;
}
</style>
